<template>
  <div class="img">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="value" v-imgerror="imageUrl" :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
      <div v-if="value" class="XoX" @click.prevent.stop="close">x</div>
    </el-upload>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDQdaGfogHbliOoxqSnrfDUUEwNXQ3RYOy',
  SecretKey: 'LPFtNcbKo44oJYXGlzygCTUFk01mHXXH'
})
export default {
  name: 'UpdateImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: require('@/assets/common/head.jpg')
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      return true
    },
    httpRequest(res) {
      cos.putObject(
        {
          Bucket: 'people-1308948000' /* 必须：存储桶，使用自己注册的存储桶 */,
          Region: 'ap-hongkong' /* 存储桶所在地域，必须字段 */,
          Key: res.file.uid + '' /* 必须，要求是字符串 */,
          StorageClass: 'STANDARD', // 固定，不用修改
          Body: res.file, // 上传文件对象
          onProgress: (progressData) => {
            // 上传进度
            console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          // 上传成功的回调  err:代表错误，没有错误就代表成功  data：上传成功的接口返回值
          console.log(err || data)
          this.$emit('input', 'http://' + data.Location)
        }
      )
    },
    close() {
      this.$emit('input', '')
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader-icon[data-v-38d1b750] {
  border: 1px dashed #d9d9d9;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.img {
  position: relative;
  &:hover {
    .avatar-uploader-icon[data-v-38d1b750] {
      border: 1px dashed #409eff;
    }
    .XoX {
      display: block;
    }
  }
  .XoX {
    position: absolute;
    top: -8px;
    right: -16px;
    color: #f91;
    display: none;
  }
}
</style>
